local Layer = _src("layer")

return pl.class {
   _init = function (self, layer_tbl)
      self.tbl = layer_tbl or {}
   end,
   
   update = function (self)
      pl.tablex.map(function (v)
	    v:update()
      end, self.tbl)
   end,
   
   add = function (self, name, z, w, h)
      local z = z or #self.tbl + 1
      local name = name or tostring(z)
      local lay = Layer(z, name, w, h)
      table.insert(self.tbl, z, lay)
      return lay
   end,
   
   add_from_str = function (self, name, z, w, h, str)
		local l = self:add(name, z, w, h)
		local idata = _li.newImageData(l.w, l.h, "rgba8", str)
		local img = love.graphics.newImage(idata)
		l.cvs:renderTo(function ()
			love.graphics.draw(img)
		end)
   end,
   
   get = function (self, name)
      local layer
      for k, l in ipairs(self.tbl) do
	 if l.name == name or l.id == tonumber(name) then
	    layer = l
	 end
      end
      return layer
   end,
   
   discard = function (self, layer)
      local layer = layer or CurrentLayer
      if #self.tbl == 1 then
	 self:add()
      end
      CurrentLayer = self.tbl[#self.tbl - 1]
      table.remove(self.tbl)
   end,
   
   merge = function (layer, layer2)
      assert(layer:is_a(Layer) and layer2:is_a(Layer))
      layer:paste(layer2)
   end,
   
   draw = function (self)
      pl.tablex.map(function (v)
	    v:draw() 
      end, self.tbl)
   end,
}
